
//操作共享遍历会有问题的售票系统代码
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<unistd.h>
#include<cstdio>
#include<pthread.h>
using namespace std;

int ticket = 1000;
pthread_spinlock_t lock; ///自旋锁

void* route(void* arg)
{
   char* id = (char*)arg;
   while(true)
   {
    //   sleep(1);
    //   printf("%s is tring to spin...\n",id);
      pthread_spin_lock(&lock); //加锁
      if(ticket > 0)
      {
         usleep(2000);
         printf("%s sells ticket:%d\n",id,ticket);
         ticket--;
         pthread_spin_unlock(&lock);//解锁
      }
      else 
      {
        sleep(2);
         pthread_spin_lock(&lock);
         break;
      }
   }
   return nullptr;
}

int main()
{  
   pthread_spin_init(&lock,PTHREAD_PROCESS_PRIVATE);//申请锁
   pthread_t t1,t2,t3,t4;
  //创建线程
   pthread_create(&t1,NULL,route,(void*)"thread-1");
   pthread_create(&t2,NULL,route,(void*)"thread-2");
   pthread_create(&t3,NULL,route,(void*)"thread-3");
   pthread_create(&t4,NULL,route,(void*)"thread-4");
    //等待线程
   pthread_join(t1,nullptr);
   pthread_join(t2,nullptr); 
   pthread_join(t3,nullptr); 
   pthread_join(t4,nullptr); 
   //销毁锁
    pthread_spin_destroy(&lock);
    return 0;
}